﻿//http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

// copy C:\Users\*\Documents\Visual Studio 2010\Addins\MVCGenerator.Addin

// annoying Script bebugger to process iexplore.exe failed
// regsvr32.exe "%ProgramFiles(x86)%\Common Files\Microsoft Shared\VS7Debug\msdbg2.dll"

// For fun Coding Styles used:
// no or limited negative logic
// intentional else's
// !using !
// !using != - code that is generated has !=
// !using ?:: - code that is generated has  ?::
// !using regular expressions
// !using viewbag except for the title.
// long function's .... sorry... fixing later.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using System.Diagnostics;
using System.IO;
using System.Xml;
using EDMXParserV1;
using MVCScaffolderXMLXML;
using Microsoft.AspNet.Scaffolding;
using MVCScaffolder;
using MVCScaffolder.Model;


namespace MVCScaffolder
{
    public partial class Form1 : Form
    {
        CodeGenerationContext Context;
        private CustomCodeGenerator CustomCodeGenerator;

        public CodeGeneratorProperty CodeGeneratorProperty = new CodeGeneratorProperty();

        public Form1(CodeGenerationContext Context, CustomCodeGenerator CustomCodeGenerator)
        {
            InitializeComponent();
            this.Context = Context;
            this.CustomCodeGenerator = CustomCodeGenerator;
        }

        public DTE applicationObject { get; set; }

        private List<EDMXParserV1.Edmx> EdmxList = new List<EDMXParserV1.Edmx>();

        private void Form1_Load(object sender, EventArgs e)
        {
            Initialize();


            if (cboEntityClass.Items.Count > 0)
            {
                cboEntityClass.SelectedIndex = 0;
            }
        }

        private String GetProjectDirectory(EnvDTE.Project P)
        {
            return P.Properties.Item("FullPath").Value.ToString();
        }

        private EnvDTE.Project GetTargetProject()
        {
            return Context.ActiveProject;
        }

        // 
        private MVCGeneratorXML XMLSettings = null;

        private void Initialize()
        {
            applicationObject = Context.ActiveProject.DTE;
            System.Array ActiveProjects = applicationObject.ActiveSolutionProjects as System.Array;

            //EnvDTE.Project FirstActiveProject = null;
            //foreach (EnvDTE.Project ActiveProject in ActiveProjects)
            //{
            //    FirstActiveProject = ActiveProject;
            //    cboProject.Items.Add(ActiveProject.Name);
            //    cboProject.SelectedValue = FirstActiveProject.Name;
            //    break;
            //}

            //foreach (EnvDTE.Project Project in applicationObject.Solution.Projects)
            {
                foreach (EnvDTE.ProjectItem ProjectItem in Context.ActiveProject.ProjectItems)
                {
                    if (ProjectItem.Name.EndsWith(".edmx"))
                    {
                        for (int i = 1; i <= ProjectItem.Properties.Count; i++)
                        {
                            if (ProjectItem.Properties.Item(i).Name == "LocalPath")
                            {
                                String FileName = ProjectItem.Properties.Item(i).Value.ToString();
                                Edmx edmx = new Edmx(FileName);
                                EdmxList.Add(edmx);
                            }
                        }
                    }
                }
            }

            //foreach (String ProjectName in EdmxSet.Keys.ToArray())
            //{
            //    cboProject.Items.Add(ProjectName);
            //}

            if (EdmxList.Count() == 0)
            {
                //
                String Message = "";
                Message = Message + "                                            This addin uses Entity Models\n";
                Message = Message + "Please Add to Project: Add->New Item->Data->ADO.NET Entity Data Model";
                MessageBox.Show(Message);
                this.Close();
            }

            // load settings file


            String SettingsFileName = Path.Combine(GetSolutionFolder(), @"MVCGenerator.XML");
            if (System.IO.File.Exists(SettingsFileName))
            {
                XmlDocument Document = new XmlDocument();
                Document.Load(SettingsFileName);
                XMLSettings = MVCGeneratorXML.CreateNewMVCGeneratorXML(Document.DocumentElement);

                try
                {
                    // Set the Add A link on View index
                    switch (XMLSettings.AddLinkToViewIndex.ToUpper())
                    {
                        case "TRUE":
                            chkAddLinkToViewIndex.Checked = true;
                            break;
                        case "FALSE":
                            chkAddLinkToViewIndex.Checked = false;
                            break;
                        default:
                            chkAddLinkToViewIndex.Checked = false;
                            break;
                    }

                }
                catch (Exception ex1)
                {

                }

                try
                {
                    switch (XMLSettings.AddScriptBundle.ToUpper())
                    {
                        case "TRUE":
                            chkAddScriptBundle.Checked = true;
                            break;
                        case "FALSE":
                            chkAddScriptBundle.Checked = false;
                            break;
                        default:
                            chkAddScriptBundle.Checked = false;
                            break;
                    }
                }
                catch (Exception ex1)
                {


                }


                try
                {
                    switch (XMLSettings.AddStyleBundle.ToUpper())
                    {
                        case "TRUE":
                            chkAddStyleBundle.Checked = true;
                            break;
                        case "FALSE":
                            chkAddStyleBundle.Checked = false;
                            break;
                        default:
                            chkAddStyleBundle.Checked = false;
                            break;
                    }
                }
                catch (Exception ex1)
                {


                }


                try
                {
                    switch (XMLSettings.AddScriptLayout.ToUpper())
                    {
                        case "TRUE":
                            chkAddScriptLayout.Checked = true;
                            break;
                        case "FALSE":
                            chkAddScriptLayout.Checked = false;
                            break;
                        default:
                            chkAddScriptLayout.Checked = false;
                            break;
                    }
                }
                catch (Exception ex1)
                {


                }

                try
                {
                    switch (XMLSettings.AddStyleLayout.ToUpper())
                    {
                        case "TRUE":
                            chkAddStyleLayout.Checked = true;
                            break;
                        case "FALSE":
                            chkAddStyleLayout.Checked = false;
                            break;
                        default:
                            chkAddStyleLayout.Checked = false;
                            break;
                    }
                }
                catch (Exception ex1)
                {

                }

                try
                {
                    switch (XMLSettings.InstallNuGet.ToUpper())
                    {
                        case "TRUE":
                            chkInstallJqueryUI.Checked = true;
                            break;
                        case "FALSE":
                            chkInstallJqueryUI.Checked = false;
                            break;
                        default:
                            chkInstallJqueryUI.Checked = false;
                            break;
                    }
                }
                catch (Exception ex1)
                {

                }
            }
            else
            {
                XMLSettings = new MVCGeneratorXML();
            }

            // Load Entity models
            cboEntityClass.Items.Clear();
            foreach (Edmx Item in EdmxList)
            {
                cboEntityClass.Items.Add(Item.Runtime.ConceptualModels.Schema.EntityContainer.Name);
            }

            if (cboEntityClass.Items.Count > 0)
            {
                cboEntityClass.SelectedIndex = 0;
            }

        }

        //private PublicProperty GetEntityPropertyFromUsableClass(UsableClass UsableClass, String NamespaceName = "", String ModelName = "")
        //{
        //    foreach (PublicProperty pp in UsableClass.Properties)
        //    {
        //        if (pp.FullTypeName == "System.Data.Objects.ObjectSet<" + NamespaceName + "." + ModelName + ">")
        //        {
        //            if (pp.IsPublic)
        //            {
        //                return pp;
        //            }
        //        }
        //    }
        //    return null;
        //}

        private bool IsGridChoiceFromSearchable(List<GridChoice> GridChoices, Searchable s)
        {
            foreach (var GridChoice in GridChoices)
            {
                if (s.ColumnName == GridChoice.ColumnName)
                {
                    return true;
                }
            }
            return false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Store the settings
            XMLSettings.AddLinkToViewIndex = chkAddLinkToViewIndex.Checked.ToString();
            XMLSettings.AddScriptBundle = chkAddScriptBundle.Checked.ToString();
            XMLSettings.AddStyleBundle = chkAddStyleBundle.Checked.ToString();

            XMLSettings.AddScriptLayout = chkAddScriptLayout.Checked.ToString();
            XMLSettings.AddStyleLayout = chkAddStyleLayout.Checked.ToString();

            XMLSettings.InstallNuGet = chkInstallJqueryUI.Checked.ToString();

            MVCGeneratorXMLEntityTypes CurrentEntityType = GetCurrentSettingsEntityType();

            // if this is the first time, make a new XMLEntityType to store the settings.
            if (CurrentEntityType == null)
            {
                CurrentEntityType = new MVCGeneratorXMLEntityTypes();
                CurrentEntityType.Project = Context.ActiveProject.Name;
                CurrentEntityType.EntityContainer = cboEntityClass.Text;
                CurrentEntityType.EntityType = cboModelClass.Text;
                XMLSettings.MVCGeneratorXMLEntityTypess.Add(CurrentEntityType);
            }

            ///Store the settings


            //textBox1.Text = "";
            //Solution2 Solution = applicationObject.Solution as Solution2;
            //Solution.AddSolutionFolder("Test-AddSolutionFolder");
            //var x = applicationObject.ActiveSolutionProjects;
            // String NamespaceName = cboProject.Text;
            String NamespaceName = GetTargetProject().Properties.Item("RootNamespace").Value.ToString();
            String EntityName = cboEntityClass.Text;
            String ModelName = cboModelClass.Text;
            //UsableClass EntityClass = null;
            //PublicProperty EntityProperty = null;



            List<GridChoice> GridChoices = new List<GridChoice>();
            List<Searchable> SearchChoices = new List<Searchable>();
            List<Sortable> SortChoices = new List<Sortable>();

            String EntityPropertyName = "";
            EntityPropertyName = SelectedEntitySet.Name;
            String PropertyClassName = "";
            PropertyClassName = SelectedEntitySet.EntityTypeLink.Name;
            String PropertyClassNameVariable = PropertyClassName.ToLower();
            String PropertyClassPrimaryKeyName = SelectedEntitySet.EntityTypeLink.Keys[0]; //PropertyClass.PrimaryKeyName;
            String PropertyClassPrimaryKeyType = SelectedEntitySet.EntityTypeLink.GetTypeName(PropertyClassPrimaryKeyName);// PropertyClass.PrimaryKeyTypeName;

            // loop through the rows in the grid
            for (int i = 0; i <= grd.Rows.Count - 1; i++)
            {

                DataGridViewRow row = grd.Rows[i];

                String FieldName = row.Cells[GridChoiceCells.FieldNameColumnIndex].Value.ToString();
                String ShowInDetailView = row.Cells[GridChoiceCells.ShowInDetailViewColumnIndex].Value.ToString();
                bool ShowInMasterView = row.Cells[GridChoiceCells.ShowInMasterViewColumnIndex].Value.ToBoolean();
                bool IsSearchable = row.Cells[GridChoiceCells.IsSearchableColumnIndex].Value.ToBoolean();
                String KeyColumn = "";
                if ( row.Cells[GridChoiceCells.KeyColumnIndex].Value == null ) 
                {
                    // Leave KeyColumn Blank
                }
                else
                {
                    KeyColumn = row.Cells[GridChoiceCells.KeyColumnIndex].Value.ToString();
                }

                String PrimaryTable = "";
                if ( row.Cells[GridChoiceCells.LinkedTableColumnIndex].Value == null ) 
                {
                    // Leave PrimaryTable Blank
                }
                else
                {
                    PrimaryTable = row.Cells[GridChoiceCells.LinkedTableColumnIndex].Value.ToString();
                }
                String DisplayColumn = "";
                if ( row.Cells[GridChoiceCells.DisplayColumnIndex].Value == null ) 
                {
                    
                }
                else
                {
                    DisplayColumn = row.Cells[GridChoiceCells.DisplayColumnIndex].Value.ToString();
                }
                String DataType = row.Cells[GridChoiceCells.TypeColumnIndex].Value.ToString();

                // prepare to store the settings in a settings file.
                MVCScaffolderXMLXML.Column CurrentColumn = null;
                foreach (MVCScaffolderXMLXML.Column Column in CurrentEntityType.Columns)
                {
                    if (Column.FieldName == FieldName)
                    {
                        if (Column.DataType == DataType)
                        {
                            // found it/already exists
                            CurrentColumn = Column;
                            break;
                        }                       
                    }
                    else
                    {
                        // no match stop searching.

                    }
                }

                // no settings in the file so create a new setting.
                if (CurrentColumn == null)
                {
                    CurrentColumn = new Column();
                    CurrentColumn.DataType = DataType;
                    CurrentColumn.FieldName = FieldName;
                    CurrentEntityType.Columns.Add(CurrentColumn);
                }

                // update the settings file.
                CurrentColumn.ComboBoxColumn = PrimaryTable;
                CurrentColumn.DisplayField = DisplayColumn;
                CurrentColumn.IsSearchable = IsSearchable.ToString();
                CurrentColumn.Key = KeyColumn;
                CurrentColumn.ShowInDetailView = ShowInDetailView;
                CurrentColumn.ShowInMasterView = ShowInMasterView.ToString();                

                // Set the IsInDetail and Master Views selection.
                foreach (EDMXParserV1.Property Property in SelectedEntitySet.EntityTypeLink.Properties)
                {
                    if (Property.Name == FieldName)
                    {
                        Property.IsInDetailView = ShowInDetailView;
                        Property.IsInMasterView = ShowInMasterView;

                        break;
                    }
                }

                if (row.Cells[GridChoiceCells.LinkedTableColumnIndex].Value.IsNull())
                {
                    // This column does not have a lookup table enabled.
                    // do nothing
                }
                else
                {
                    // This column is being used with a lookup table.
                    GridChoice GridCoice = new GridChoice();
                    GridCoice.ColumnName = FieldName;
                    GridCoice.PrimaryKey = KeyColumn;
                    GridCoice.PrimaryTable = PrimaryTable;
                    GridCoice.DisplayColumnName = DisplayColumn;

                    // see if the Grid drop down list supports null fields.
                    // so foreign key table or null
                    foreach (var item in SelectedEntitySet.EntityTypeLink.Properties)
                    {
                        if (item.Name == GridCoice.ColumnName)
                        {
                            foreach (NavigationProperty CurrentNavigationProperty in SelectedEntitySet.EntityTypeLink.NavigationProperties)
                            {
                                if (CurrentNavigationProperty.FromRole == PropertyClassName)
                                {
                                    if (CurrentNavigationProperty.ToRole == GridCoice.PrimaryTable)
                                    {
                                        foreach (AssociationEnd CurrentAssocationEnd in CurrentNavigationProperty.Association.AssociationEnds)
                                        {
                                            if (CurrentAssocationEnd.Role == GridCoice.PrimaryTable)
                                            {
                                                String Multiplicity = CurrentAssocationEnd.Multiplicity;

                                                if (Multiplicity.StartsWith("0.."))
                                                {
                                                    GridCoice.CanLinkedTableBeNull = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                    GridChoices.Add(GridCoice);
                }

                if (row.Cells[GridChoiceCells.IsSearchableColumnIndex].Value.IsNull())
                {
                    // the cell is not marked searchable.
                }
                else
                {
                    IsSearchable = Convert.ToBoolean(row.Cells[GridChoiceCells.IsSearchableColumnIndex].Value);
                }

                if (IsSearchable)
                {
                    Searchable Searchable = new Searchable();
                    Searchable.ColumnName = FieldName;
                    Searchable.IsSearchable = true;
                    foreach (var item in SelectedEntitySet.EntityTypeLink.Properties)
                    {
                        if (Searchable.ColumnName == item.Name)
                        {
                            Searchable.Property = item;
                            item.Searchable = Searchable;
                            break;
                        }
                    }
                    SearchChoices.Add(Searchable);
                }

                // currently marking everything as sortable
                // originally it was an option.
                Sortable Sortable = new Sortable();
                Sortable.ColumnName = FieldName;
                Sortable.IsSortable = true;
                foreach (var item in SelectedEntitySet.EntityTypeLink.Properties)
                {
                    if (Sortable.ColumnName == item.Name)
                    {
                        Sortable.Property = item;
                        item.Sortable = Sortable;
                        break;
                    }
                }
                SortChoices.Add(Sortable);
            }

            // precalculate Searchable
            foreach (Searchable Searchable in SearchChoices)
            {
                foreach (GridChoice GridChoice in GridChoices)
                {
                    if (Searchable.ColumnName == GridChoice.ColumnName)
                    {
                        GridChoice.Searchable = Searchable;
                        Searchable.GridChoice = GridChoice;
                        break;
                    }
                }
            }

            bool UsingDropDownLists = false;

            foreach (EDMXParserV1.NavigationProperty item in SelectedEntitySet.EntityTypeLink.NavigationProperties)
            {
                foreach (var GridChoiceItem in GridChoices)
                {
                    if (item.Name == GridChoiceItem.PrimaryTable)
                    {
                        UsingDropDownLists = true;
                        break;
                    }
                }

                if (UsingDropDownLists == true)
                {
                    break;
                }
            }


     foreach (GridChoice GridChoice in GridChoices)
	 {
        foreach (EDMXParserV1.NavigationProperty Item in SelectedEntitySet.EntityTypeLink.NavigationProperties)
        {
            if (GridChoice.PrimaryTable == Item.Name)
            {
                if (Item.ToEntityType != null)
                {
                    foreach (EDMXParserV1.Property Property in Item.ToEntityType.Properties)
                    {
                        if (Property.Name == GridChoice.DisplayColumnName)
                        {
                            foreach (EDMXParserV1.EntitySet EntitySet in SelectedEDMX.Runtime.ConceptualModels.Schema.EntityContainer.EntitySets)
                            {
                                if (EntitySet.EntityTypeLink.Name == Item.ToRole || EntitySet.Name == Item.ToRole)
                                {
                                    GridChoice.ToEntitySet = EntitySet;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
      }


            CodeGeneratorProperty.EntityPropertyName = EntityPropertyName;
            CodeGeneratorProperty.GridChoices = GridChoices;
            CodeGeneratorProperty.NamespaceName = NamespaceName;
            CodeGeneratorProperty.PropertyClassName = PropertyClassName;
            CodeGeneratorProperty.PropertyClassNameVariable = PropertyClassNameVariable;
            CodeGeneratorProperty.PropertyClassPrimaryKeyName = PropertyClassPrimaryKeyName;
            CodeGeneratorProperty.PropertyClassPrimaryKeyType = PropertyClassPrimaryKeyType;
            CodeGeneratorProperty.SearchChoices = SearchChoices;
            CodeGeneratorProperty.SelectedEDMX = SelectedEDMX;
            CodeGeneratorProperty.SelectedEntitySet = SelectedEntitySet;
            CodeGeneratorProperty.SortChoices = SortChoices;
            CodeGeneratorProperty.UsingDropDownLists = UsingDropDownLists;
            CodeGeneratorProperty.EntityClassName = SelectedEDMX.Runtime.Mappings.Mapping.EntityContainerMapping.CdmEntityContainer;

            CodeGeneratorProperty.AddScriptBundle = chkAddScriptBundle.Checked;
            CodeGeneratorProperty.AddStyleBundle = chkAddStyleBundle.Checked;

            CodeGeneratorProperty.AddScriptLayout = chkAddScriptLayout.Checked;
            CodeGeneratorProperty.AddStyleLayout = chkAddStyleLayout.Checked;

            CodeGeneratorProperty.InstallNuGet = chkInstallJqueryUI.Checked;

            CodeGeneratorProperty.AddLinkToViewIndex = chkAddLinkToViewIndex.Checked;

            //ControllersCS ControllerCS = new ControllersCS(CodeGeneratorProperty);
            
            //// Make Controllers directory if needed
            //String ProjectDirectoryName = GetProjectDirectory(GetTargetProject());

            //String ControllersDirectoryName = System.IO.Path.Combine(ProjectDirectoryName, "Controllers");

            //if (System.IO.Directory.Exists(ControllersDirectoryName) == false)
            //{
            //    AddToTextBox1("Creating folder: " + ControllersDirectoryName);
            //    System.IO.Directory.CreateDirectory(ControllersDirectoryName);
            //}

            //// Make views directory if needed
            //String ViewsDirectoryName = System.IO.Path.Combine(ProjectDirectoryName, "Views");

            //String TargetViewDirectoryName = System.IO.Path.Combine(ViewsDirectoryName, EntityPropertyName);

            //if (System.IO.Directory.Exists(TargetViewDirectoryName) == false)
            //{
            //    AddToTextBox1("Creating Directory: " + TargetViewDirectoryName);
            //    System.IO.Directory.CreateDirectory(TargetViewDirectoryName);
            //}

            //// See if the Controller.cs file is already in the project folder.
            //String TargetControllerFileName = System.IO.Path.Combine(ControllersDirectoryName, EntityPropertyName + "Controller.cs");
            //Boolean TargetControllerExists = false;
            //if (System.IO.File.Exists(TargetControllerFileName))
            //{
            //    TargetControllerExists = true;
            //}

            //// write the source code.
            //System.IO.File.WriteAllText(TargetControllerFileName, ControllerCS.ToString());
            //AddToTextBox1("Writing: " + EntityPropertyName + "Controller.cs " + ControllerCS.ToString().Length + " bytes");

            //// if the Controller.cs file didn't exist, then add the file to the project.
            //if (TargetControllerExists == false)
            //{
            //    // add to project
            //    GetTargetProject().ProjectItems.AddFromFile(TargetControllerFileName);
            //    AddToTextBox1("Adding to project: " + TargetControllerFileName);
            //}

            //CreateCSHtml CreateCSHTML = new CreateCSHtml(CodeGeneratorProperty);

            ////Dictionary<string, object> CreateCSHTMLParameters = new Dictionary<string, object>();
            ////CreateCSHTMLParameters.Add("NamespaceName", NamespaceName);
            ////CreateCSHTMLParameters.Add("PropertyClassName", PropertyClassName);
            ////CreateCSHTMLParameters.Add("UsingDropDownLists", UsingDropDownLists);

            ////this.CustomCodeGenerator.AFFT(Context.ActiveProject,
            ////    "CreateCSHtmlvvvv",
            ////    "CreateCSHtml",
            ////    CreateCSHTMLParameters,
            ////    skipIfExists: false);

            //CreateViewDirectoryInProjectIfNecessary(TargetViewDirectoryName);
            
            //String ViewCreateFilename = System.IO.Path.Combine(TargetViewDirectoryName, "Create.cshtml");
            //Boolean ViewCreateFilenameExists = System.IO.File.Exists(ViewCreateFilename);

            //System.IO.File.WriteAllText(ViewCreateFilename, CreateCSHTML.ToString());
            //AddToTextBox1("Writing: Create.cshtml" + CreateCSHTML.ToString().Length + " bytes");

            //if (ViewCreateFilenameExists == false)
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(ViewCreateFilename);
            //}

            ////Edit.cshtml
            //EditCSHtml EditCSHtml = new MVCScaffolder.EditCSHtml(CodeGeneratorProperty);
                        
            //String ViewEditFilename = System.IO.Path.Combine(TargetViewDirectoryName, "Edit.cshtml");

            //Boolean ViewEditFilenameExists = System.IO.File.Exists(ViewEditFilename);

            //System.IO.File.WriteAllText(ViewEditFilename, EditCSHtml.ToString());
            //AddToTextBox1("Writing: Edit.schtml " + EditCSHtml.ToString().Length + " bytes");

            //if (ViewEditFilenameExists == false)
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(ViewEditFilename);
            //}

            ////Index.cshtml
            //IndexCSHtml IndexCSHtml = new MVCScaffolder.IndexCSHtml(CodeGeneratorProperty);

            //String TargetViewIndexFilename = System.IO.Path.Combine(TargetViewDirectoryName, "Index.cshtml");

            //Boolean TargetViewIndexFilenameExists = System.IO.File.Exists(TargetViewIndexFilename);

            //System.IO.File.WriteAllText(TargetViewIndexFilename, IndexCSHtml.ToString());
            //AddToTextBox1("Writing File: Index.cshtml " + IndexCSHtml.ToString().Length + " bytes");

            //if (TargetViewIndexFilenameExists == false)
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(TargetViewIndexFilename);
            //}

            ////Details.cshtml
            //DetailsCSHtml DetailsCSHtml = new MVCScaffolder.DetailsCSHtml(CodeGeneratorProperty);
            //String ViewDetailsFilename = System.IO.Path.Combine(TargetViewDirectoryName, "Details.cshtml");

            //Boolean ViewDetailsFilenameExists = System.IO.File.Exists(ViewDetailsFilename);
            //System.IO.File.WriteAllText(ViewDetailsFilename, DetailsCSHtml.ToString());
            //AddToTextBox1("Writing Details.cshtml " + DetailsCSHtml.ToString().Length + " bytes ");

            //if (ViewDetailsFilenameExists == false)
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(ViewDetailsFilename);
            //}

            ////Delete.cshtml
            //DeleteCSHtml DeleteCSHtml = new MVCScaffolder.DeleteCSHtml(CodeGeneratorProperty);
            //String ViewDeleteFilename = System.IO.Path.Combine(TargetViewDirectoryName, "Delete.cshtml");
            //Boolean ViewDeleteFilenameExists = System.IO.File.Exists(ViewDeleteFilename);
            //System.IO.File.WriteAllText(ViewDeleteFilename, DeleteCSHtml.ToString());
            //AddToTextBox1("Writing Delete.cshtml " + DeleteCSHtml.ToString().Length + " bytes");

            //if (ViewDeleteFilenameExists == false)
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(ViewDeleteFilename);
            //}

            ////_CreateOrEdit.cshtml

            //CreateOrEditcshtml CreateOrEditcshtml = new MVCScaffolder.CreateOrEditcshtml(CodeGeneratorProperty);

            //String CreateOrEditFilename = System.IO.Path.Combine(TargetViewDirectoryName, "_CreateOrEdit.cshtml");

            //Boolean CreateOrEditFilenameExists = System.IO.File.Exists(CreateOrEditFilename);

            //System.IO.File.WriteAllText(CreateOrEditFilename, CreateOrEditcshtml.ToString());
            //AddToTextBox1("Writing: _CreateOrEdit.cshtml " + CreateOrEditcshtml.ToString().Length + " bytes");

            //if (CreateOrEditFilenameExists == false)
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(CreateOrEditFilename);
            //}

            //// Models
            //ModelsCS Models = new ModelsCS(NamespaceName, GridChoices, SearchChoices, SortChoices, PropertyClassName, SelectedEntitySet);

            //String ModelsDirectoryName = System.IO.Path.Combine(ProjectDirectoryName, "Models");

            //if (System.IO.Directory.Exists(ModelsDirectoryName) == false)
            //{
            //    System.IO.Directory.CreateDirectory(ModelsDirectoryName);
            //}

            //String ModelFilename = System.IO.Path.Combine(ModelsDirectoryName, EntityPropertyName + "Models.cs");

            //Boolean ModelFilenameExists = System.IO.File.Exists(ModelFilename);

            //System.IO.File.WriteAllText(ModelFilename, Models.ToString());
            //AddToTextBox1("Writing Models.cs " + Models.ToString().Length + " bytes");

            //if (ModelFilenameExists == false)
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(ModelFilename);
            //}
              
            //// Add Base/BasicIndexPage.cs
            //String ModelsBasePath = System.IO.Path.Combine(ModelsDirectoryName, "Base");
            //if (System.IO.Directory.Exists(ModelsBasePath))
            //{
            //    // Modes/Base already exists.
            //}
            //else
            //{
            //    // the Modes/Base directory is not on the file system, create it.
            //    System.IO.Directory.CreateDirectory(ModelsBasePath);
            //}

            //// Build the path to the BasicIndexPage.cs file.
            //String BasicIndexPageFileName = System.IO.Path.Combine(ModelsDirectoryName, "Base", "BasicIndexPage.cs");
            //bool BasicIndexPageFileExists = System.IO.File.Exists(BasicIndexPageFileName);

            ////todo
            //BasicIndexPage BasicIndexPage = new BasicIndexPage();
            //System.IO.File.WriteAllText(BasicIndexPageFileName, BasicIndexPage.ToString());
            ////Write File here.
            ////

            //if (BasicIndexPageFileExists)
            //{
            //    // File Already exists no need to add to project.
            //}
            //else
            //{
            //    GetTargetProject().ProjectItems.AddFromFile(BasicIndexPageFileName);
            //}

            /////Add Base/BasicIndexPage.cs

            //bool AddLinkToViewIndex = chkAddLinkToViewIndex.Checked;

            //String ViewIndexFileName = System.IO.Path.Combine(ViewsDirectoryName,"Home", "Index.cshtml");

            //if (System.IO.File.Exists(ViewIndexFileName))
            //{
            //    String ViewIndexText = System.IO.File.ReadAllText(ViewIndexFileName);
            //    String LinkSourceCode = @"<br />@Html.ActionLink(""" + ModelName + @""", ""Index"", """ + ModelName + @""")";

            //    if (ViewIndexText.Contains(LinkSourceCode))
            //    {
            //        // The link is already in the file,
            //        // don't add the link.
            //    }
            //    else
            //    {
            //        // Add the link to the end of the file.
            //        StreamWriter sr = System.IO.File.AppendText(ViewIndexFileName);
            //        sr.WriteLine();
            //        sr.WriteLine(LinkSourceCode);
            //        sr.Close();
            //    }
            //}
            //else
            //{
            //    // the files not there don't do anything.
            //}

            CodeGeneratorProperty.AddScriptBundle = chkAddScriptBundle.Checked;
            CodeGeneratorProperty.AddStyleBundle = chkAddStyleBundle.Checked;


            XMLSettings.Save(GetSolutionFolder());
            //AddToTextBox1("Done !  Close this window and reload any files you have open.");

            // close Form
            Close();
        }

        private MVCGeneratorXMLEntityTypes GetCurrentSettingsEntityType()
        {
            MVCGeneratorXMLEntityTypes CurrentEntityType = null;

            // See if there is an existing settings file.
            foreach (MVCGeneratorXMLEntityTypes XMLEntityType in XMLSettings.MVCGeneratorXMLEntityTypess)
            {
                //if (XMLEntityType.Project == cboProject.Text)
                {
                    if (XMLEntityType.EntityContainer == cboEntityClass.Text)
                    {
                        if (XMLEntityType.EntityType == cboModelClass.Text)
                        {
                            // Found an existing save from the settings.
                            CurrentEntityType = XMLEntityType;
                            break;
                        }
                    }
                }
            }
            return CurrentEntityType;
        }

        private void CreateViewDirectoryInProjectIfNecessary(String TargetViewDirectoryName)
        {
            Boolean ViewDirectoryExists = System.IO.Directory.Exists(TargetViewDirectoryName);
            if (ViewDirectoryExists == false)
            {
                AddToTextBox1("Adding Directory: " + TargetViewDirectoryName);
                System.IO.Directory.CreateDirectory(TargetViewDirectoryName);

                GetTargetProject().ProjectItems.AddFromDirectory(TargetViewDirectoryName);
            }
        }

        private Edmx SelectedEDMX;

        private void cboEntityClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            cboModelClass.Items.Clear();

            foreach (Edmx Item in EdmxList)
            {
                if (Item.Runtime.ConceptualModels.Schema.EntityContainer.Name == cboEntityClass.Text)
                {
                    SelectedEDMX = Item;
                    //foreach (EDMXParserV1.EntityType EntityType in Item.Runtime.StorageModels.Schema.EntityTypes)
                    //{
                    //    cboModelClass.Items.Add(EntityType.Name);
                    //}
                    foreach (var item in Item.Runtime.ConceptualModels.Schema.EntityContainer.EntitySets)
                    {
                        cboModelClass.Items.Add(item.Name);
                    }

                    break;
                }
            }

            if (cboModelClass.Items.Count > 0)
            {
                cboModelClass.SelectedIndex = 0;
            }

        }

        private void LoadOptionsGrid()
        {
            //Solution2 Solution = applicationObject.Solution as Solution2;
            //Solution.AddSolutionFolder("Test-AddSolutionFolder");
            //var x = applicationObject.ActiveSolutionProjects;
            String NamespaceName = Context.ActiveProject.Name;
            String EntityName = cboEntityClass.Text;
            String ModelName = cboModelClass.Text;

            //UsableClass EntityClass = null;
            //PublicProperty EntityProperty = null;

            //UsableClass PropertyClass = null;
            //foreach (KeyValuePair<String, UsableClass> UsableClass in Lst)
            //{
            //    if (UsableClass.Value.FullName ==  ModelName)
            //    {

            //        EntityClass = UsableClass.Value;
            //    }
            //}

            //foreach (PublicProperty pp in  EntityClass.Properties)
            //{
            //    if (pp.FullName == ModelName)
            //    {
            //        EntityProperty = pp;
            //    }
            //}

            //foreach (KeyValuePair<String, UsableClass> UsableClass in Lst)
            //{
            //    if (UsableClass.Value.FullName == EntityProperty.TemplateUsingClassName)
            //    {
            //        PropertyClass = UsableClass.Value;
            //    }
            //}

            //PropertyClass = Lst[cboProject.Text + "." + "Group"];

            //String EntityPropertyName = EntityProperty.Name;
            //String PropertyClassName = SelectedEntitySet.EntityTypeLink.Name;
            //String PropertyClassNameVariable = PropertyClassName.ToLower();

            // warning.
            String PropertyClassPrimaryKeyName = "";

            if (SelectedEntitySet.EntityTypeLink != null)
            {
                PropertyClassPrimaryKeyName = SelectedEntitySet.EntityTypeLink.Keys[0];// PropertyClass.PrimaryKeyName;
            }

            //List<Relationship> CurrentRelationships = new List<Relationship>();
            //foreach (Relationship  R in Relationships)
            //{
            //    if (R.DependentTable == PropertyClassName)
            //    {
            //        if (R.FileName == PropertyClass.FullPath)
            //        {
            //            CurrentRelationships.Add(R);
            //        }
            //    }
            //}

            grd.Rows.Clear();
            grd.DataSource = null;

            //primary

            MVCGeneratorXMLEntityTypes CurrentEntityType = GetCurrentSettingsEntityType();

            if (SelectedEntitySet.EntityTypeLink != null)
            {
                foreach (EDMXParserV1.Property p in SelectedEntitySet.EntityTypeLink.Properties)
                {

                    MVCScaffolderXMLXML.Column CurrentSettingColumn = GetCurrentSettingsColumnFromProperty(CurrentEntityType, p);


                    int RowID = grd.Rows.Add();
                    grd.Rows[RowID].Cells[GridChoiceCells.FieldNameColumnIndex].Value = p.Name;
                    grd.Rows[RowID].Cells[GridChoiceCells.TypeColumnIndex].Value = p.Type;


                    (grd.Rows[RowID].Cells[GridChoiceCells.ShowInMasterViewColumnIndex] as DataGridViewCheckBoxCell).Value = "True";
                    if (CurrentSettingColumn == null)
                    {
                        // Leave the box in the default state.
                    }
                    else
                    {
                        // Blindly reading the fields from an external file, might as well make it handle junk inputs.
                        switch (CurrentSettingColumn.ShowInMasterView.ToUpper())
                        {
                            case "TRUE":
                                (grd.Rows[RowID].Cells[GridChoiceCells.ShowInMasterViewColumnIndex] as DataGridViewCheckBoxCell).Value = "True";
                                break;
                            case "FALSE":
                                (grd.Rows[RowID].Cells[GridChoiceCells.ShowInMasterViewColumnIndex] as DataGridViewCheckBoxCell).Value = "False";
                                break;
                            default:
                                // Leave the default
                                break;
                        }
                    }
                    //(grd.Rows[RowID].Cells[GridChoiceCells.ShowInDetailViewColumnIndex] as DataGridViewCheckBoxCell).Value = "True";

                    DataGridViewComboBoxCell cboShowInDetailView = grd.Rows[RowID].Cells[GridChoiceCells.ShowInDetailViewColumnIndex] as DataGridViewComboBoxCell;
                    cboShowInDetailView.Items.Add("No");
                    cboShowInDetailView.Items.Add("View");
                    cboShowInDetailView.Items.Add("Edit");

                    // Default is Edit.
                    cboShowInDetailView.Value = "Edit";

                    if (CurrentSettingColumn == null)
                    {
                        // Leave the default if there is no config file.
                    }
                    else
                    {
                        // Blindly reading the fields from an external file, might as well make it handle junk inputs.
                        switch (CurrentSettingColumn.ShowInDetailView.ToUpper())
                        {
                            case "EDIT":
                                cboShowInDetailView.Value = "Edit";
                                break;
                            case "NO":
                                cboShowInDetailView.Value = "No";
                                break;
                            case "VIEW":
                                cboShowInDetailView.Value = "View";
                                break;
                            default:
                                // Leave the default.
                                break;
                        }
                    }

                    // Is Searchable
                    if (CurrentSettingColumn == null)
                    {
                        // Leave default, default is unchecked.
                        //(grd.Rows[RowID].Cells[IsSearchableColumnIndex] as DataGridViewCheckBoxCell).Value = "True";

                    }
                    else
                    {
                        // Blindly reading the fields from an external file, might as well make it handle junk inputs.
                        switch (CurrentSettingColumn.IsSearchable.ToUpper())
                        {
                            case "TRUE":
                                (grd.Rows[RowID].Cells[GridChoiceCells.IsSearchableColumnIndex] as DataGridViewCheckBoxCell).Value = "True";
                                break;
                            case "FALSE":
                                (grd.Rows[RowID].Cells[GridChoiceCells.IsSearchableColumnIndex] as DataGridViewCheckBoxCell).Value = "False";
                                break;
                            default:
                                // Leave the default
                                break;
                        }
                    }


                    bool FoundOne = false;
                    // need to core load this.
                    foreach (var item in SelectedEntitySet.EntityTypeLink.NavigationProperties)
                    {
                        String TableName = item.Name;
                        String SchemaNamespaceName = SelectedEDMX.Runtime.ConceptualModels.Schema.Namespace;

                        Association CurrentAssociation = item.Association;

                        if (PropertyClassPrimaryKeyName == p.Name)
                        {
                            // Uncheck the primary key column by default.
                            (grd.Rows[RowID].Cells[GridChoiceCells.ShowInMasterViewColumnIndex] as DataGridViewCheckBoxCell).Value = "False";
                            //(grd.Rows[RowID].Cells[GridChoiceCells.ShowInDetailViewColumnIndex] as DataGridViewCheckBoxCell).Value = "False";

                            // Default primary key to No
                            cboShowInDetailView.Value = "No";

                            // Can change a primary key.
                            cboShowInDetailView.Items.Remove("Edit");
                        }
                        else
                        {
                            if (item.Association.ReferentialConstraint.IsNotNull())
                            {
                                if (
                                    item.Association.ReferentialConstraint.Dependent.PropertyRefs[0].Name == p.Name
                                    ||
                                    item.Association.ReferentialConstraint.Principal.PropertyRefs[0].Name == p.Name
                                    )
                                // if (true)
                                {
                                    String RoleName = item.Association.ReferentialConstraint.Principal.Role;

                                    AssociationEnd CurrentAssociationEnd = null;
                                    foreach (AssociationEnd AssociationEnd in item.Association.AssociationEnds)
                                    {
                                        if (AssociationEnd.Role == RoleName)
                                        {
                                            CurrentAssociationEnd = AssociationEnd;
                                            break;
                                        }
                                    }

                                    DataGridViewComboBoxCell cboTables = grd.Rows[RowID].Cells[GridChoiceCells.LinkedTableColumnIndex] as DataGridViewComboBoxCell;
                                    cboTables.Items.Add("");
                                    cboTables.Items.Add(item.Name);
                                    cboTables.Value = item.Name;

                                    //grd.Rows[RowID].Cells[3].Value = item.FromEntityType.Keys[0].ToString();
                                    //grd.Rows[RowID].Cells[3].Value = p.Name;
                                    grd.Rows[RowID].Cells[GridChoiceCells.KeyColumnIndex].Value = item.Association.ReferentialConstraint.Principal.PropertyRefs[0].Name;

                                    FoundOne = true;
                                    cboTables = grd.Rows[RowID].Cells[GridChoiceCells.DisplayColumnIndex] as DataGridViewComboBoxCell;

                                    String SelectedOne = "";

                                    String DisplayFieldUsedInSettings = "";


                                    if (CurrentAssociationEnd.EntityType != null)
                                    {
                                        foreach (EDMXParserV1.Property Property in CurrentAssociationEnd.EntityType.Properties)
                                        {
                                            cboTables.Items.Add(Property.Name);

                                            // See if Name is in one of the fields, mark it as a potential autopick.
                                            if (Property.Name.ToLower().Contains("name"))
                                            {
                                                SelectedOne = Property.Name;
                                            }

                                            // See if desc is in one of the fields, mark it as a potential autopick. ( hrm )
                                            if (Property.Name.ToLower().Contains("desc"))
                                            {
                                                SelectedOne = Property.Name;
                                            }

                                            // check to see if this column is in the settings file.
                                            if (Property.Name.ToLower() == CurrentSettingColumn.DisplayField.ToLower())
                                            {
                                                DisplayFieldUsedInSettings = Property.Name;
                                            }
                                        }
                                    }

                                    if (cboTables.Items.Count > 0)
                                    {
                                        if (DisplayFieldUsedInSettings == "")
                                        {
                                            // try using a name or desc.
                                            if (SelectedOne.Length == 0)
                                            {
                                                cboTables.Value = cboTables.Items[0].ToString();
                                            }
                                            else
                                            {
                                                cboTables.Value = SelectedOne;
                                            }
                                        }
                                        else
                                        {
                                            // found it in the config file.
                                            cboTables.Value = DisplayFieldUsedInSettings;
                                        }
                                    }
                                    break;
                                }
                            }
                            else
                            {
                                // no referential constraint
                                // do nothing

                            }
                            //if (item.ToEntityType  != null && p.Name == item.Association.ReferentialConstraint.Dependent.PropertyRefs[0].Name && item.ToEntityType != null )
                            //{

                            //}
                        }
                    }

                    // if there was no linked table disable the cell.
                    if (FoundOne == false)
                    {
                        DataGridViewComboBoxCell cbo = grd.Rows[RowID].Cells[GridChoiceCells.LinkedTableColumnIndex] as DataGridViewComboBoxCell;
                        cbo.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;

                        cbo = grd.Rows[RowID].Cells[GridChoiceCells.DisplayColumnIndex] as DataGridViewComboBoxCell;
                        cbo.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                    }
                }
            }
        }


        /// <summary>
        /// Locates the CurrentSettingFrom the settingsList
        /// </summary>
        /// <param name="CurrentEntityType"></param>
        /// <param name="p">EDMXParserV1.Property</param>
        /// <returns>Setting Column if found, NULL if missing.</returns>
        private static MVCScaffolderXMLXML.Column GetCurrentSettingsColumnFromProperty(MVCGeneratorXMLEntityTypes CurrentEntityType, EDMXParserV1.Property p)
        {
            MVCScaffolderXMLXML.Column CurrentColumn = null;
            if (CurrentEntityType == null)
            {
                CurrentColumn = new Column();
            }
            else
            {
                // try to find a match.
                foreach (MVCScaffolderXMLXML.Column Column in CurrentEntityType.Columns)
                {
                    if (Column.FieldName == p.Name)
                    {
                        if (Column.DataType == p.Type)
                        {
                            // found it
                            CurrentColumn = Column;
                            break;
                        }
                    }
                    else
                    {

                    }
                }
            }
            return CurrentColumn;
        }

        private void cboProject_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //private List<EntityMapping> EntityMappingList = new List<EntityMapping>();

        //private void ProcessEntitySetMapping(String FileName, XmlNode Node)
        //{
        //    EntityMapping EntityMapping = new EntityMapping();

        //    foreach (XmlNode ChildNode in Node.ChildNodes)
        //    {
        //        String[] TypeName = ChildNode.Attributes["TypeName"].Value.Split('.');
        //        EntityMapping.ClassName = TypeName[TypeName.Length - 1];

        //        foreach (XmlNode SubChildNode in ChildNode.ChildNodes)
        //        {
        //            String MissingFragmentStoreEntitySet = SubChildNode.Attributes["StoreEntitySet"].Value;
        //            EntityMapping.ClassSetName = MissingFragmentStoreEntitySet;

        //            foreach (XmlNode SubSubChildNode in SubChildNode.ChildNodes)
        //            {
        //                String Name = SubSubChildNode.Attributes["Name"].Value;
        //                String ColumnName = SubSubChildNode.Attributes["ColumnName"].Value;

        //                EntityMappingProperty EMP = new EntityMappingProperty();
        //                EMP.ColumnName = ColumnName;
        //                EMP.Name = Name;

        //                EntityMapping.List.Add(EMP);
        //            }
        //        }
        //    }

        //    EntityMappingList.Add(EntityMapping);
        //}

        private List<Relationship> Relationships = new List<Relationship>();

        private void ProcessAssociation(String FileName, XmlNode Node)
        {

            foreach (XmlNode ChildNode in Node.ChildNodes)
            {
                if (ChildNode.Name == "ReferentialConstraint")
                {
                    Relationship Relationship = new Relationship();
                    Relationship.FileName = FileName.Replace(".edmx", ".Designer.cs");
                    foreach (XmlNode InnerNode in ChildNode.ChildNodes)
                    {
                        if (InnerNode.Name == "Principal")
                        {
                            String Role = InnerNode.Attributes.GetNamedItem("Role").Value;
                            Relationship.PrimaryTable = Role;
                            foreach (XmlNode ChildPrincipalNode in InnerNode.ChildNodes)
                            {
                                if (ChildPrincipalNode.Name == "PropertyRef")
                                {
                                    String Key = ChildPrincipalNode.Attributes.GetNamedItem("Name").Value;
                                    Relationship.PrimaryKey = Key;
                                }
                            }
                        }
                        if (InnerNode.Name == "Dependent")
                        {
                            String Role = InnerNode.Attributes.GetNamedItem("Role").Value;
                            Relationship.DependentTable = Role;
                            foreach (XmlNode ChildPrincipalNode in InnerNode.ChildNodes)
                            {
                                if (ChildPrincipalNode.Name == "PropertyRef")
                                {
                                    String Key = ChildPrincipalNode.Attributes.GetNamedItem("Name").Value;
                                    Relationship.DependentKey = Key;
                                }
                            }
                        }

                    }
                    String Key2 = Relationship.DependentKey + "/" + Relationship.DependentTable + "/" + Relationship.FileName + "/" + Relationship.PrimaryKey + "/" + Relationship.PrimaryTable;
                    foreach (Relationship r in Relationships)
                    {
                        String Key1 = r.DependentKey + "/" + r.DependentTable + "/" + r.FileName + "/" + r.PrimaryKey + "/" + r.PrimaryTable;

                        if (Key1 == Key2)
                        {
                            break;
                        }
                    }

                    //if (FoundOne == false)
                    //{
                    //    foreach (KeyValuePair<String, UsableClass> UsableClass in Lst)
                    //    {
                    //        if (UsableClass.Value.FullPath == Relationship.FileName)
                    //        {

                    //            Relationship.UsableClass = UsableClass.Value;
                    //            UsableClass.Value.Relationships.Add(Relationship);
                    //            break;
                    //        }
                    //    } 
                    //    Relationships.Add(Relationship);
                    //}

                }
            }
        }


        private void grd_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (grd.IsCurrentCellDirty)
            {
                grd.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }

            if (grd.CurrentCell.GetType().ToString() == "System.Windows.Forms.DataGridViewComboBoxCell")
            {
                if (grd.CurrentCell.ColumnIndex == 2)
                {
                    //DataGridViewComboBoxCell cboDisplay = grd.CurrentRow.Cells[3] as DataGridViewComboBoxCell;
                    //cboDisplay.Items.Clear();
                    //DataGridViewComboBoxCell cboKey = grd.CurrentRow.Cells[4] as DataGridViewComboBoxCell;
                    //cboKey.Items.Clear();
                    //UsableClass UsableClass = Lst[cboProject.Text + "." + grd.CurrentCell.Value];
                    //foreach (PublicProperty item in UsableClass.Properties)
                    //{
                    //    if (item.IsPublic)
                    //    {
                    //        cboDisplay.Items.Add(item.Name);
                    //        cboKey.Items.Add(item.Name);
                    //    }
                    //}
                }
            }
        }

        private void cmdCheckForValidation_Click(object sender, EventArgs e)
        {
            //Context.ActiveProject 
            //foreach (EnvDTE.Project Project in applicationObject.Solution.Projects)
            //{

            foreach (EnvDTE.ProjectItem ProjectItem in Context.ActiveProject.ProjectItems)
            {
                if (ProjectItem.Name == "Views")
                {
                    foreach (EnvDTE.ProjectItem ViewsItem in ProjectItem.ProjectItems)
                    {
                        if (ViewsItem.Name == "Shared")
                        {
                            foreach (EnvDTE.ProjectItem SharedItem in ViewsItem.ProjectItems)
                            {
                                if (SharedItem.Name == "_Layout.cshtml")
                                {
                                    foreach (EnvDTE.Property Property in SharedItem.Properties)
                                    {
                                        var x = Property.ToString();
                                        if (Property.Name == "FullPath")
                                        {
                                            var Text = System.IO.File.ReadAllText(Property.Value.ToString());
                                            bool containsjqueryvalidatemin = false;
                                            bool containsjqueryunobtrusiveajaxminjs = false;
                                            bool containsjqueryvalidateunobtrusiveminjs = false;
                                            bool containsjqueryui = false;
                                            bool ContainsJqueryUIAllCss = false;


                                            containsjqueryvalidatemin = Text.Contains("jquery.validate.min.js");
                                            containsjqueryunobtrusiveajaxminjs = Text.Contains("jquery.unobtrusive-ajax.min.js");
                                            containsjqueryvalidateunobtrusiveminjs = Text.Contains("jquery.validate.unobtrusive.min.js");
                                            containsjqueryui = Text.Contains("jquery-ui");
                                            ContainsJqueryUIAllCss = Text.Contains("jquery.ui.all.css");

                                            bool containsSlashHead = Text.Contains("</head>");

                                            bool showmessage = false;
                                            if (containsjqueryunobtrusiveajaxminjs == false)
                                            {
                                                AddToTextBox1("Missing: jquery.unobtrusive-ajax.min.js");
                                                showmessage = true;
                                            }

                                            if (containsjqueryvalidatemin == false)
                                            {
                                                showmessage = true;
                                                AddToTextBox1("Missing: jquery.validate.min.js");
                                            }

                                            if (containsjqueryvalidateunobtrusiveminjs == false)
                                            {
                                                showmessage = true;
                                                AddToTextBox1("Missing: jquery.validate.unobtrusive.min.js");
                                            }

                                            if (containsjqueryui == false)
                                            {
                                                showmessage = true;
                                                AddToTextBox1("Missing: jquery-ui-1.8.11.min.js");
                                            }

                                            if (ContainsJqueryUIAllCss == false)
                                            {
                                                showmessage = true;
                                                AddToTextBox1("Missing: jquery.ui.all.css");
                                            }

                                            if (showmessage)
                                            {
                                                DialogResult Result = MessageBox.Show("Missing jquery references, add them?", "Add jquery references", MessageBoxButtons.YesNo);
                                                if (Result == System.Windows.Forms.DialogResult.Yes)
                                                {
                                                    int Location = Text.IndexOf("</head>");

                                                    if (containsjqueryunobtrusiveajaxminjs == false)
                                                    {
                                                        Text = Text.Insert(Location, @"    <script src=""@Url.Content(""~/Scripts/jquery.unobtrusive-ajax.min.js"")"" type=""text/javascript""></script>" + "\r\n");
                                                        AddToTextBox1("Added: jquery.unobtrusive-ajax.min.js");
                                                    }

                                                    if (containsjqueryvalidateunobtrusiveminjs == false)
                                                    {
                                                        Text = Text.Insert(Location, @"    <script src=""@Url.Content(""~/Scripts/jquery.validate.unobtrusive.min.js"")"" type=""text/javascript""></script>" + "\r\n");
                                                        AddToTextBox1("Added: jquery.validate.unobtrusive.min.js");
                                                    }
                                                    if (containsjqueryvalidatemin == false)
                                                    {
                                                        Text = Text.Insert(Location, @"    <script src=""@Url.Content(""~/Scripts/jquery.validate.min.js"")"" type=""text/javascript""></script>" + "\r\n");
                                                        AddToTextBox1("Added: jquery.validate.min.js");
                                                    }

                                                    if (containsjqueryui == false)
                                                    {
                                                        // see if it exists.
                                                        Text = Text.Insert(Location, @"    <script src=""@Url.Content(""~/Scripts/jquery-ui-1.8.11.min.js"")"" type=""text/javascript""></script>" + "\r\n");
                                                        AddToTextBox1("Added: jquery-ui-1.8.11.min.js");
                                                    }

                                                    if (ContainsJqueryUIAllCss == false)
                                                    {
                                                        Text = Text.Insert(Location, @"    <link href=""@Url.Content(""~/Content/themes/base/jquery.ui.all.css"")"" rel=""stylesheet"" type=""text/css""></link>" + "\r\n");
                                                        AddToTextBox1("Added: jquery.ui.all.css");
                                                    }

                                                    System.IO.File.WriteAllText(Property.Value.ToString(), Text);
                                                }
                                            }
                                        }
                                    }

                                    var resutl = SharedItem;
                                }
                            }
                        }
                    }
                }
            }

        }

        EDMXParserV1.EntitySet SelectedEntitySet = null;

        private void cboModelClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (EntitySet ES in SelectedEDMX.Runtime.ConceptualModels.Schema.EntityContainer.EntitySets)
            {
                //suspect
                //if (ES.EntityTypeLink.Name == cboModelClass.Text)
                if (ES.Name == cboModelClass.Text)
                {
                    SelectedEntitySet = ES;
                    break;
                    //foreach (EDMXParserV1.EntityType item in SelectedEDMX.Runtime.ConceptualModels.Schema.EntityTypes )
                    //{
                    //    if (ES.EntityTypeLink.Name == item.Name)
                    //    {
                    //        SelectedEntitySet = ES;
                    //        break;
                    //    }
                    //}       
                }
                //if (item.EntityTypeLink.Name  == cboModelClass.Text)
                //{
                //    SelectedEntitySet = item;

                //}
            }
            //foreach (EDMXParserV1.EntityType EntityType in SelectedEDMX.Runtime.ConceptualModels.Schema.EntityTypes)
            //{
            //    if (EntityType.Name == cboModelClass.Text)
            //    {
            //        SelectedEntityType = EntityType;
            //    }
            //}

            LoadOptionsGrid();
        }

        private void AddToTextBox1(String s)
        {
            //textBox1.Text = s + "\r\n" + textBox1.Text;
        }

        private String GetSolutionFolder()
        {
            String SolutionName = applicationObject.Solution.FullName;
            String[] Keys = SolutionName.Split('\\');
            if (Keys.Length > 0)
            {
                // remove the solution name.
                return SolutionName.Replace(Keys[Keys.Length - 1], "");
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Selects all the check boxes of the MouseMenuColumnIndex
        /// MouseMenuColumnIndex is set by right clicking in the grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow Row in grd.Rows)
            {
                Row.Cells[MouseMenuColumnIndex].Value = true;
            }
        }

        //' used to determine which the column the popup menu was created with.
        private int MouseMenuColumnIndex = 0;

        /// <summary>
        /// When clicked brings up a popup menu ( Select All, Select None )
        /// Identifies which column is rigth clicked, 
        /// Stores in MouseMenuColumnIndex 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grd_MouseDown(object sender, MouseEventArgs e)
        {
            //' if there is a right click in the grid
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {

                //' position in the grid.
                Point MousePosition = grd.PointToClient(Control.MousePosition);

                //' cell in the grid.
                System.Windows.Forms.DataGridView.HitTestInfo MouseLocationInGrid = grd.HitTest(MousePosition.X, MousePosition.Y);

                const int MasterViewGridColumnIndex = 2;
                const int DetailViewGridColumnIndex = 4;
                const int MenuOffset = -5;

                //' show a popup menu for the Master or Detail column.
                if (MouseLocationInGrid.ColumnIndex == MasterViewGridColumnIndex || MouseLocationInGrid.ColumnIndex == DetailViewGridColumnIndex)
                {

                    //'actuall show the popup menu.
                    SelectorMenu.Show(this.Left + grd.Left + MousePosition.X + MenuOffset, this.Top + grd.Top + MousePosition.Y + MenuOffset);

                    //' store the location to be used when the popup menu is clicked.
                    MouseMenuColumnIndex = MouseLocationInGrid.ColumnIndex;
                }
            }
        }

        /// <summary>
        /// Clears all the check boxes of the MouseMenuColumnIndex
        /// MouseMenuColumnIndex is set by right clicking in the grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow Row in grd.Rows)
            {
                Row.Cells[MouseMenuColumnIndex].Value = false;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void chkAddLinkToViewIndex_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {

        }
    }

    public static class Xyz
    {
        public static String Value(this CodeElement Expression)
        {
            String Result = Expression.GetStartPoint().CreateEditPoint().GetText(Expression.GetEndPoint());
            if (Expression.Name.Length > 0)
            {
                Result = Result.Replace(Expression.Name, "");
            }
            Result = Result.Replace("=", "");
            return Result;
        }

    }
}

public class GridChoiceCells
{
    public static int FieldNameColumnIndex = 0;
    public static int TypeColumnIndex = 1;
    public static int ShowInMasterViewColumnIndex = 2;
    public static int ShowInDetailViewColumnIndex = 3;
    public static int IsSearchableColumnIndex = 4;
    public static int LinkedTableColumnIndex = 5;
    public static int KeyColumnIndex = 6;
    public static int DisplayColumnIndex = 7;
}
